# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: auto_range.py
  @time: 2022/6/16 9:03
  @desc:
"""
"""
Imeas>0.9*range，Range up，  Imeas＜0.1*range，range down
"""
import numpy as np


def auto_range(current_value, current_range):
    range_list = ["1uA", "10uA", "100uA", "1mA", "10mA", "120mA"]
    range_dict = {"1uA": 1E-6, "10uA": 1E-5, "100uA": 1E-4, "1mA": 1E-3, "10mA": 1E-2, "120mA": 0.12}
    current_index = range_list.index(current_range)
    is_variety = False
    if float(current_value) > float(range_dict[current_range]) * 0.8:
        if current_index < len(range_list):
            current_range = range_list[current_index + 1]
            is_variety = True
    elif float(current_value) < float(range_dict[current_range]) * 0.08:
        if current_index > 0:
            current_range = range_list[current_index - 1]
            is_variety = True
    current_limit = range_dict[current_range]
    return is_variety, current_range, current_limit


def n7744_auto_range(meas_data, current_range):
    range_list = ["10", "0", "-10", "-20", "-30"]
    current_index = range_list.index(str(int(float(current_range))))
    max_value = max(meas_data)
    is_variety = False
    if float(max_value) >= float(current_range) * 0.9:
        if current_index > 0:
            current_range = range_list[current_index - 1]
            is_variety = True
    elif current_index < len(range_list) - 1 and float(max_value) < float(range_list[current_index + 1]) * 0.9:
        current_range = range_list[current_index + 1]
        is_variety = True
    return is_variety, current_range


def find_nearest(value,current_range):
    array = [10, 0, -10, -20, -30]
    is_variety = False
    array = np.asarray(array)
    find_value = np.abs(array - value)
    print(find_value)
    idx = find_value.argmin()
    if float(value) >= array[idx] and idx > 0:
        is_variety = True
        idx = idx - 1
    return is_variety, array[idx]


# range_list = [10, 0, -10, -20, -30]
# print(n7744_auto_range(-10, -10))

# print(find_nearest(-10,-10))
